package com.tj.jinzao.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tandong.bottomview.view.BottomView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tj.jinzao.App;
import com.tj.jinzao.R;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 我的认证界面
 * Created by wjy on 2019/1/5.
 */
public class InviteFriendActivity extends BaseActivity {

    private String mInviteCode;
    private Bitmap mQrBitmap;

    @BindView(R.id.iv_qrcode)
    ImageView mQrCodeView;
    @BindView(R.id.tv_code)
    TextView mCodeView;
    @BindView(R.id.bt_share)
    Button bt_share;
    @BindView(R.id.image_lay)
    LinearLayout image_lay;

    private BottomView bottomView;
    private IWXAPI api;
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }
    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }
    //保存图片
    private void showPopWindowImage(){
        bottomView=new BottomView(InviteFriendActivity.this, com.netease.nim.uikit.R.style.BottomViewTheme_Defalut, com.netease.nim.uikit.R.layout.item_select);
        bottomView.setAnimation(com.netease.nim.uikit.R.style.myStyle);
        bottomView.dismissBottomView();
        bottomView.showBottomView(false);
        TextView txt_1= bottomView.getView().findViewById(com.netease.nim.uikit.R.id.txt_1);
        TextView txt_2= bottomView.getView().findViewById(com.netease.nim.uikit.R.id.txt_2);
        View view_line=bottomView.getView().findViewById(com.netease.nim.uikit.R.id.view_line);
        view_line.setVisibility(View.GONE);
        txt_1.setText("保存图片");
        txt_2.setVisibility(View.GONE);
        TextView txt_exit= bottomView.getView().findViewById(com.netease.nim.uikit.R.id.txt_exit);
        txt_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                saveImageToGallery(InviteFriendActivity.this, mQrBitmap);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if(imageQrUrl!=null&&!imageQrUrl.equals("")){
                            Bitmap bp = returnBitMap(imageQrUrl);
                            saveImageToGallery(InviteFriendActivity.this, bp);
                        }

                    }
                }).start();
                ToastUtils.showToast(InviteFriendActivity.this,"保存成功");
                bottomView.dismissBottomView();

            }
        });
        txt_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomView.dismissBottomView();
            }
        });

    }
    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片 创建文件夹
        File appDir = new File(Environment.getExternalStorageDirectory(), "shy");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        //图片文件名称
        String fileName = "shy_"+System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        String path = file.getAbsolutePath();
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), path, fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
    }


    @Override
    public int getLayoutResource() {
        return R.layout.activity_invite_friend;
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @Override
    protected void setupView() {
        super.setupView();
//        api = WXAPIFactory.createWXAPI(this, Constant.WX_APPID, false);
        api = WXAPIFactory.createWXAPI(this, Constant.WX_APPID);
        api.registerApp(Constant.WX_APPID);

        mInviteCode = UserManager.getInstance().getUser().getRequestCode();
        mCodeView.setText(mInviteCode);

        getImageUrl();
        image_lay.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
//                if(mQrBitmap!=null){
                    showPopWindowImage();
//                }
                return false;
            }
        });

    }
    private String imageUrl,imageQrUrl;
    private void getImageUrl(){
        addSubscription(mApiService.getWXImageUrl(), new SubscriberCallBack<String>(this) {
            @Override
            protected void onSuccess(String list) {
                imageUrl=Constant.IMAGE_PREFIX+list;
                bytes=Util.getHtmlByteArray(imageUrl);
            }

            @Override
            protected void onFailure(ResultResponse response) {

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });
        HashMap<String,Object> map=new HashMap<>();
        map.put("uid",UserManager.getInstance().getUser().getId());
        addSubscription(mApiService.getQR(map), new SubscriberCallBack<String>(this) {
            @Override
            protected void onSuccess(String list) {
                imageQrUrl=Constant.IMAGE_PREFIX+list;
                Glide.with(InviteFriendActivity.this).load(imageQrUrl).into(mQrCodeView);

//                Glide.with(InviteFriendActivity.this).load(Constant.IMAGE_PREFIX+list).into(new SimpleTarget<Drawable>() {
//                    @Override
//                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
////                        BitmapDrawable bd = (BitmapDrawable) resource;
////                        mQrBitmap =bd.getBitmap();
////                        mQrCodeView.setImageBitmap(mQrBitmap);
//
//                    }
//                });
            }

            @Override
            protected void onFailure(ResultResponse response) {

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });

    }
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    private byte[] bytes;
    /**
     * 将URL转化成bitmap形式
     *
     * @param url
     * @return bitmap type
     */
    public final static Bitmap returnBitMap(String url) {
        URL myFileUrl;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
            HttpURLConnection conn;
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    private void showPopWindow(){
        bottomView=new BottomView(InviteFriendActivity.this, R.style.BottomViewTheme_Defalut, R.layout.share_item_pop);
        bottomView.setAnimation(R.style.myStyle);
        bottomView.dismissBottomView();
        bottomView.showBottomView(false);
        TextView exit=bottomView.getView().findViewById(R.id.exit);
        LinearLayout lay_1=bottomView.getView().findViewById(R.id.lay_1);
        LinearLayout lay_2=bottomView.getView().findViewById(R.id.lay_2);
        LinearLayout lay_3=bottomView.getView().findViewById(R.id.lay_3);
        LinearLayout lay_4=bottomView.getView().findViewById(R.id.lay_4);
        lay_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Util.shareWeb(InviteFriendActivity.this,api,SendMessageToWX.Req.WXSceneSession);
                bottomView.dismissBottomView();
            }
        });
        lay_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(InviteFriendActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        lay_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(InviteFriendActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        lay_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                //初始化一个 WXTextObject 对象，填写分享的文本内容
                Util.shareWeb(InviteFriendActivity.this,api,SendMessageToWX.Req.WXSceneTimeline);
                bottomView.dismissBottomView();
            }
        });
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomView.dismissBottomView();
            }
        });

    }


    @Override
    protected void initLinstener() {
        bt_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopWindow();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        detachView();
        App.isShare=false;
        if (mQrBitmap != null && !mQrBitmap.isRecycled()) {
            mQrBitmap.recycle();
        }
        mQrBitmap=null;
    }
}
